package com.pangu.util.rules.model;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.ActionTaskUtils;
import com.pangu.core.engine.game.BeiMiGameEvent;
import com.pangu.core.engine.game.model.PlayerRecordJinhua;
import com.pangu.core.engine.game.model.Summary;
import com.pangu.core.engine.game.model.SummaryPlayer;
import com.pangu.util.GameUtils;
import com.pangu.util.ProcessCard;
import com.pangu.util.TimeUtil;
import com.pangu.util.ai.AIAction;
import com.pangu.util.disruptor.DisruptorHandler;
import com.pangu.web.model.GamePlayway;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.PlayUserClient;
import com.pangu.web.service.impl.BroadcastServiceImpl;
import com.pangu.web.service.repository.es.PlayUserClientESRepository;
import com.pangu.web.service.repository.es.PlayerRecordJinhuaESRepository;
import com.pangu.web.service.repository.jpa.PlayUserClientRepository;
import com.pangu.web.service.repository.jpa.PlayerRecordJinhuaRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * Description:炸金花牌局信息
 *
 * @author abo
 * @date 2018年4月16日
 */
@Slf4j
public class ZhajinhuaBoard extends Board implements java.io.Serializable {

	/**
	 * Description:
	 */
	private static final long serialVersionUID = 1L;
	
	public ZhajinhuaBoard() {
	}

	@Override
	public byte[] pollLastHands() {
		return null;
	}

	@Override
	public int calcRatio() {
		return 1;
	}

	@Override
	public TakeCards takeCards(Player player, String playerType, TakeCards current) {
		return null;
	}

	@Override
	public int index(String userid) {
		int index = 0;
		for (int i = 0; i < this.getPlayers().length; i++) {
			Player temp = this.getPlayers()[i];
			if (temp.getPlayuser().equals(userid)) {
				index = i;
				break;
			}
		}
		return index;
	}

	@Override
	public Summary summary(Board board, GameRoom gameRoom, GamePlayway playway) {
		Summary summary = new Summary(gameRoom.getId(), board.getId(), board.getRatio(), 0);
		List<PlayUserClient> plays = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameRoom.getId(),
				gameRoom.getOrgi());
		// Map<String, Object> map = ProcessCard.whoIsWinner(board);// 红胜还是黑胜
		// int whoWin = Integer.parseInt(map.get("flag").toString());
		// board.setWinner(whoWin + "");// 加入谁赢了
		double tem = 0.00;
		SummaryPlayer summaryPlayer = null;

		// 获取牌局所有的下注记录
		double temSum = 0;// 当局输赢总量
		for (PlayUserClient playUserClient : plays) {
			// 获取此用户的下注记录
			List<PlayerRecordJinhua> prList = (List<PlayerRecordJinhua>) CacheHelper.getGameRecordJinhuaCacheBean()
					.getCacheObject(playUserClient.getId(), playUserClient.getOrgi());
			for (PlayerRecordJinhua pr : prList) {
				temSum += pr.getCoin();
			}
		}
		// 初始化房间没真人了。不会再次开局了，当在下面匹配到还有真人，那么牌局继续开始
		summary.setGameRoomOver(true);
		// 根据下注记录进行结算。
		for (PlayUserClient playUserClient : plays) {
			// 获取此用户的下注记录
			List<PlayerRecordJinhua> prList = (List<PlayerRecordJinhua>) CacheHelper.getGameRecordJinhuaCacheBean()
					.getCacheObject(playUserClient.getId(), playUserClient.getOrgi());
			double betCount = 0;// 下注金额
			for (PlayerRecordJinhua pr : prList) {
				betCount += pr.getCoin();
			}
			Player player = player(playUserClient.getId());
			PlayerRecordJinhua pr = new PlayerRecordJinhua();
			// 封装结算对象，返回给前端
			summaryPlayer = new SummaryPlayer(playUserClient.getId(), playUserClient.getUsername(), 0, 0,
					tem > 0 ? true : false, false);
			// 判断是不是活到最后的人，活到最后的人就是赢家，没被比输、没有弃牌的玩家
			if (!player.isEnd() && !player.isHu()) {
				board.setWinner(player.getPlayuser());// 牌局赢家
				summaryPlayer.setWin(true);
				playUserClient.setGoldcoins(playUserClient.getGoldcoins() - betCount + (new Double(temSum)).intValue());// 赢了等于余额减去投注金额加上牌局投注总额
				pr.setWinLoseCoin(temSum - betCount);// 赢了就等于牌局总额减投注金额
			} else {
				playUserClient.setGoldcoins(playUserClient.getGoldcoins() - betCount);// 输了就等于余额减去投注金额
				pr.setWinLoseCoin(0 - betCount);// 输了就等于投注额
			}
			// CacheHelper.getGamePlayerCacheBean().put(playUserClient.getId(),
			// playUserClient, gameRoom.getOrgi());
			// 持久化用户数据
			DisruptorHandler.published(playUserClient,
					BMDataContext.getContext().getBean(PlayUserClientESRepository.class),
					BMDataContext.getContext().getBean(PlayUserClientRepository.class));
			// 记录日志
			pr.setRoomId(gameRoom.getId());// 房间id
			pr.setOrgi(gameRoom.getOrgi());
			pr.setCoin(betCount);
			pr.setGameId(board.getId());
			// 本局牌型
			String c = ProcessCard.byteCardToString(player.getCards());// byteCardToRedBlackString(player.getCards());
			pr.setCards(c);
			pr.setGameType(BMDataContext.GameTypeEnum.JINHUA.toString());
			// pr.setSummaryId(UKTools.getUUID());// 暂时写一个，没跟结算有联系
			pr.setPlayerId(playUserClient.getId());
			pr.setPlayerType(playUserClient.getPlayertype().equals(BMDataContext.BEIMI_GAME_AI) ? "2" : "1");
			DisruptorHandler.published(pr, BMDataContext.getContext().getBean(PlayerRecordJinhuaESRepository.class),
					BMDataContext.getContext().getBean(PlayerRecordJinhuaRepository.class));

			// 当赢得本局金额总量大于此金额的时候保存在广播表，并进行广播
			if (BMDataContext.BEIMI_BROADCAST_VALUE < temSum) {
				BroadcastServiceImpl broadcastServiceImpl = BMDataContext.getContext()
						.getBean(BroadcastServiceImpl.class);
				broadcastServiceImpl.saveAndSendSocketBroadcast(playUserClient, temSum,
						BMDataContext.GameTypeEnum.JINHUA.toString());
			}
			// 结算完成就删除
			CacheHelper.getGameRecordJinhuaCacheBean().delete(playUserClient.getId(), playUserClient.getOrgi());

			summaryPlayer.setScore(pr.getWinLoseCoin());// 输赢金额
			summaryPlayer.setBalance(playUserClient.getGoldcoins());
			summary.getPlayers().add(summaryPlayer);

			// // 如果真人客户已经离开房间变成托管玩家，那么结算完就删除游戏房间的相关信息
			// PlayUserClient puc = (PlayUserClient) CacheHelper.getApiUserCacheBean()
			// .getCacheObject(playUserClient.getId(), gameRoom.getOrgi());
			// if (puc != null &&
			// (puc.getPlayertype().equals(BMDataContext.PlayerTypeEnum.OFFLINE.toString())
			// ||
			// puc.getPlayertype().equals(BMDataContext.PlayerTypeEnum.LEAVE.toString()))) {
			// CacheHelper.getGamePlayerCacheBean().delete(playUserClient.getId(),
			// playUserClient.getOrgi());
			// CacheHelper.getRoomMappingCacheBean().delete(playUserClient.getId(),
			// playUserClient.getOrgi());
			// }
			// if
			// (playUserClient.getPlayertype().equals(BMDataContext.PlayerTypeEnum.NORMAL.toString()))
			// {
			// // 匹配到还有真人，那么牌局继续开始
			// summary.setGameRoomOver(false);
			// }
			// 需要时用房间的人员（起码要有一个普通玩家）和最大标准人数比较，如果没满就放入队列
			GameUtils.changeRoomQuene(gameRoom.getId(), gameRoom.getPlayway());
		}
		board.setFinished(true);
		CacheHelper.getBoardCacheBean().put(board.getRoom(), board, gameRoom.getOrgi());
		return summary;
	}

	@Override
	public boolean isWin() {
		return false;
	}

	@Override
	protected Player next(int index) {
		return null;
	}

	@Override
	public Player nextPlayer(int index) {
		if (index == (this.getPlayers().length - 1)) {
			index = 0;
		} else {
			index = index + 1;
		}
		return this.getPlayers()[index];
	}

	@Override
	public TakeCards takecard(Player player, boolean allow, byte[] playCards) {
		return null;
	}

	@Override
	public TakeCards takecard(Player player) {
		return null;
	}

	@Override
	public TakeCards takeCardsRequest(GameRoom gameRoom, Board board, Player player, String orgi, boolean auto,
			byte[] playCards) {
		Player next = board.nextPlayer(board.index(player.getPlayuser()));
		board.setNextplayer(new NextPlayer(next.getPlayuser(), false));
//		CacheHelper.getBoardCacheBean().put(gameRoom.getId(), board, gameRoom.getOrgi());

		ZhajinhuaTakeCards zhajinhuaTakeCards = new ZhajinhuaTakeCards();
		zhajinhuaTakeCards.setRoomId(gameRoom.getId());

		PlayUserClient playUserClient = ActionTaskUtils.getPlayUserClient(gameRoom.getId(), player.getPlayuser(), orgi);
		// log.info("-------当前用户" + playUserClient.getId() + "----下个用户" +
		// board.getNextplayer().getNextplayer() + "----是"
		// + playUserClient.getPlayertype());
		if (board.getBanker().equals(playUserClient.getId())) {
			zhajinhuaTakeCards.setBanker(playUserClient.getId());
		}
		if (playUserClient != null) {
			// 当前时间往后推15秒，超时时间戳
			String timeoutStr = TimeUtil.getDateString(new Date(), null, null, null, null, null,
					BMDataContext.JINHUA_NORMAL_GAME_TIME, TimeUtil.PATTERN_STANDARD);
			zhajinhuaTakeCards.setTimeoutStr(timeoutStr);
			zhajinhuaTakeCards.setPlayerType(playUserClient.getPlayertype());
			zhajinhuaTakeCards.setUserid(player.getPlayuser());
			zhajinhuaTakeCards.setCurrentRatio(board.getRatio());
			zhajinhuaTakeCards.setOver(false);// 牌局未结束
			// 当前操作的人员放到gameroom的parentId
//			gameRoom.setParentid(playUserClient.getId());
//			CacheHelper.getGameRoomCacheBean().put(gameRoom.getId(), gameRoom, BMDataContext.SYSTEM_ORGI); 
			// 是否弃牌，是否被淘汰，判断是不是存活用户
			if (!player.isEnd() && !player.isHu()) {
				if (!BMDataContext.PlayerTypeEnum.AI.toString().equals(playUserClient.getPlayertype())) {
					zhajinhuaTakeCards.setTime(BMDataContext.JINHUA_NORMAL_GAME_TIME);
					log.info("真人间隔时间为" + zhajinhuaTakeCards.getTime() + ";userId=" + zhajinhuaTakeCards.getUserid() + ";");
					// 往前端发送信息
//					ActionTaskUtils.sendEvent("zhajinhuapretakecards", zhajinhuaTakeCards, gameRoom);
//					GameUtils.getGame(gameRoom.getPlayway(), orgi).change(gameRoom, BeiMiGameEvent.PLAYCARDS.toString(),
//							zhajinhuaTakeCards.getTime());
				} else {
					// 如果不是真人有没有弃牌，那么执行下面内容，生成ai动作
					zhajinhuaTakeCards = AIAction.generateAIAction(zhajinhuaTakeCards, board, player);
					int sleepTime = AIAction.randomRaito(5, 10);
					zhajinhuaTakeCards.setTime(sleepTime);
					// 把ai的动作往前端发送
//					ActionTaskUtils.sendEvent("zhajinhuapretakecards", zhajinhuaTakeCards, gameRoom);
					log.info("间隔时间为" + sleepTime + ";userId=" + zhajinhuaTakeCards.getUserid() + ";做了什么="
							+ zhajinhuaTakeCards.getActionType());
//					GameUtils.getGame(gameRoom.getPlayway(), orgi).change(gameRoom, BeiMiGameEvent.PLAYCARDS.toString(),
//							sleepTime);
				}
				ActionTaskUtils.sendEvent("zhajinhuapretakecards", zhajinhuaTakeCards, gameRoom);
				board.setZhajinhuaTakeCardss(zhajinhuaTakeCards);
//				GameUtils.getGame(gameRoom.getPlayway(), orgi).change(gameRoom, BeiMiGameEvent.PLAYCARDS.toString(),
//						zhajinhuaTakeCards.getTime());
			} else {
				// 弃牌或者比牌失败的用户等待0秒
				// zhajinhuaTakeCards.setTime(BMDataContext.JINHUA_ZERO_TIME);
				// GameUtils.getGame(gameRoom.getPlayway(), orgi).change(gameRoom,
				// BeiMiGameEvent.PLAYCARDS.toString(),
				// zhajinhuaTakeCards.getTime());
//				BMDataContext.getZhajinhuaEngine().takeCardsRequest(zhajinhuaTakeCards.getRoomId(),
//						board.getNextplayer().getNextplayer(), gameRoom.getOrgi(), true, null);
				zhajinhuaTakeCards.setTime(BMDataContext.JINHUA_ZERO_TIME);
			}
			CacheHelper.getBoardCacheBean().put(gameRoom.getId(), board, gameRoom.getOrgi());
			GameUtils.getGame(gameRoom.getPlayway(), orgi).change(gameRoom, BeiMiGameEvent.PLAYCARDS.toString(),
					zhajinhuaTakeCards.getTime());
		}
		return null;
	}

	@Override
	public void dealRequest(GameRoom gameRoom, Board board, String orgi, boolean reverse, String nextplayer) {

	}

	@Override
	public void playcards(Board board, GameRoom gameRoom, Player player, String orgi) {

	}

	@Override
	public TakeCards takecard(Player player, TakeCards last) {
		return null;
	}

	/**
	 * 找到玩家
	 * 
	 * @param board
	 * @param userid
	 * @return
	 */
	public Player player(String userid) {
		Player target = null;
		for (Player temp : this.getPlayers()) {
			if (temp.getPlayuser().equals(userid)) {
				target = temp;
				break;
			}
		}
		return target;
	}
	
	/**
	 * 
	 * Description:  获取当前牌局存活人数和看牌人数
	 * 
	 * @author abo
	 * @date 2018年6月13日  
	 * @return
	 */
	public Map<String,String> getBoardInfo(){
		Map<String,String> map = new HashMap<String,String>();
		//存活人数
		int livePlayer = 0;
		//看牌人数
		int lookCardPlayer = 0;		
		for (Player player : this.getPlayers()) {
			if(!player.isHu() && !player.isEnd()) {
				livePlayer += 1;
			}
			if(player.isDocatch()) {
				lookCardPlayer += 1;
			}
		}
		map.put("livePlayer", livePlayer + "");
		map.put("lookCardPlayer", lookCardPlayer + "");
		return map;
	}
	 

}
